import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_todolist/db/db.dart';
import 'package:flutter_todolist/db/table/user_table.dart';
import 'package:flutter_todolist/pages/home/home.dart';
import 'package:flutter_todolist/util.dart';
import 'package:flutter_todolist/utils/auth.dart';
import 'package:flutter_todolist/utils/common.dart';
import 'package:flutter_todolist/utils/extention.dart';
import 'package:flutter_todolist/widgets/text_input.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:image_picker/image_picker.dart';

import '../../utils/get_storage.dart';
import '../../widgets/app_button.dart';

class InfoSetting extends StatefulWidget {
  InfoSetting({
    Key? key,
    required this.userInfo,
    this.logOut = false
  }) : super(key: key);

  final User userInfo;
  bool? logOut;

  @override
  State<InfoSetting> createState() => _InfoSettingState();
}

class _InfoSettingState extends State<InfoSetting> {

  late TextEditingController ageCtrl;
  late TextEditingController nameCtrl;

  @override
  void initState() {
    ageCtrl = TextEditingController(text: widget.userInfo.age.toString());
    nameCtrl = TextEditingController(text: widget.userInfo.name);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Container(
            child: Column(
              children: [
               Container(
                 color: const Color(0xFFfbb217),
                 height: 200.h,
                 // child: 'info_setting_bg1'.assetsImg(),
               ),
               Expanded(child:  Container(color: const Color(0xFFdbedcd))),
              ],
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            child: Container(
              color: Colors.black.withOpacity(0.2),
            )
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            top: 0,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 400.h,
                  margin: EdgeInsets.symmetric(vertical: 30.h, horizontal: 30.w),
                  // padding: EdgeInsets.all(15.w),
                  // color: const Color(0xfffffaef),
                  color: const Color(0xFFfffad3),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Stack(
                            children: [
                              GestureDetector(
                                onTap: () async {
                                  XFile? xFile = await ImagePicker().pickImage(source: ImageSource.gallery);
                                  if (xFile != null) {
                                    setState(() {
                                      widget.userInfo.avatar = xFile.path;
                                    });
                                  }
                                },
                                child: Container(
                                  child: widget.userInfo.avatar!.isEmpty
                                      ? "default_avatar".assetsImg(width: 120.r, height: 160.r, fit: BoxFit.cover)
                                      : Image.file(File(widget.userInfo.avatar!), width: 120.r, height: 160.r, fit: BoxFit.cover),
                                ),
                              ),
                              Positioned(
                                  bottom: 0,
                                  right: 0,
                                  child: Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(8),
                                        color: Colors.black26
                                    ),
                                    padding: EdgeInsets.all(2.r),
                                    child: Icon(Icons.edit, size: 20, color: Colors.white),
                                  )
                              )
                            ],
                          ),

                          15.w.wSizedBox(),
                          Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 5.h),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(8),
                                        color: Color(0xFFfbb217)
                                    ),
                                    child: Text("Hello", style: GoogleFonts.ubuntu(
                                        fontWeight: FontWeight.bold, fontSize: 18.sp, letterSpacing: 3.0, color: Colors.white)),
                                  ),
                                  15.h.hSizedBox(),
                                  Text("I'm", style: GoogleFonts.ubuntu(
                                      fontWeight: FontWeight.bold, fontSize: 20.sp, color: Color(0xFF333333))),
                                  Row(
                                    children: [
                                      Expanded(
                                          child: AppTextInput(
                                            hintText: "What's your name",
                                            controller: nameCtrl,
                                            style: GoogleFonts.ubuntu(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 18.sp,
                                            ),
                                          )
                                      )
                                    ],
                                  )
                                ],
                              )
                          )
                        ],
                      ).marginAll(15.r),
                      Column(
                        children: [
                          infoPanel('Age', Expanded(
                              child: AppTextInput(
                                controller: ageCtrl,
                                hintText: "your age",
                                hintStyle: TextStyle(fontSize: 14.sp, color: Color(0xFFBCBCBC), fontWeight: FontWeight.bold),
                                contentPadding: EdgeInsets.only(bottom: 2.h),
                                inputFormatter: [
                                  FilteringTextInputFormatter.digitsOnly
                                ],
                                keyboardType: TextInputType.number,
                                style: GoogleFonts.ubuntu(
                                  fontSize: 18.sp,
                                ),
                              )
                          )),
                          infoPanel('Gender', Expanded(
                              child: Row(
                                children: [
                                  gender(0, widget.userInfo.gender == 0 ? true : false),
                                  gender(1, widget.userInfo.gender == 1 ? true : false)
                                ],
                              )
                          )),
                        ],
                      ).marginSymmetric(horizontal: 15.w),
                      Expanded(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 100.w,
                                height: 40.h,
                                child: AppButton(
                                  height: 40.h,
                                  content: 'Edit',
                                  // color: const Color(0xFF0048f8),
                                  gradientColors: const [
                                    CustomColors.PurpleDark,
                                    CustomColors.PurpleAccent,
                                  ],
                                  // color: CustomColors.PurpleAccent,
                                  onTap: () {
                                    edit();
                                  },
                                ),
                              )
                            ],
                          )
                      ),
                      Container(
                        height: 60.h,
                        color: const Color(0xFF52668b),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: const [
                            FaIcon(FontAwesomeIcons.twitter, size: 30, color: Colors.white),
                            Icon(Icons.facebook, size: 30, color: Colors.white),
                            FaIcon(FontAwesomeIcons.instagram, size: 30, color: Colors.white),
                          ],
                        ),
                      )
                    ],
                  ),
                ).animate().scale(),
                widget.logOut == true ? SizedBox(
                  width: 150.w,
                  child: AppButton(
                    content: 'LogOut',
                    gradientColors: const [
                      CustomColors.PurpleDark,
                      CustomColors.PurpleAccent,
                    ],
                    onTap: () {
                      logOut();
                    },
                  ),
                ) : const SizedBox()
              ],
            )
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              height: 30.h,
              color: const Color(0xFF52668b),
            )
          ),
          Positioned(
            left: 15.w,
            top: 40.h,
            child: GestureDetector(
              onTap: () => Get.back(),
              child: Icon(Icons.arrow_back_rounded, size: 30.r, color: Colors.white),
            )
          )
        ],
      ),
    );
  }
  
  Widget infoPanel(String title, Widget content) {
    return Row(
      children: [
        Container(
          width: 100.w,
          // color: Colors.red.withOpacity(0.2),
          child: Text(title, style: GoogleFonts.ubuntu(
            fontSize: 18.sp,
          )),
        ),
        content
      ],
    ).marginOnly(bottom: 10.h);
  }

  Widget gender(int type, bool highLight) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widget.userInfo.gender = type;
        });
      },
      child: Container(
        width: 50.w,
        height: 30.h,
        color: highLight == true ? (
            type == 0 ? CustomColors.GreenIcon.withOpacity(0.4) : CustomColors.PurpleLight.withOpacity(0.4)
        ) : Colors.grey.withOpacity(0.4),
        child: Center(
          child: FaIcon(
              type == 0 ? FontAwesomeIcons.mars : FontAwesomeIcons.venus,
              size: 20.r,
              color: highLight == true ? (
                  type == 0 ? CustomColors.GreenIcon : CustomColors.PurpleLight
              ) : Colors.grey
          ),
        ),
      ),
    );
  }

  void edit() {
    widget.userInfo.name = nameCtrl.text;
    widget.userInfo.age = int.parse(ageCtrl.text);

    AppStorage().write(AppStorage.UserInfo, widget.userInfo.toJson());

    UserTable userTable = ToDoDB().userTable;
    userTable.updateItem(widget.userInfo.userId, widget.userInfo.toJson());

    if (widget.logOut == true) {
      showToast('更新个人信息成功');
    } else {
      Get.to(() => const Home());
    }
  }

  void logOut() {
    Auth.logOut();
  }
}
